using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;

public class RecordLine : MonoBehaviour
{
    public float distance = 1f;
    public Color color = Color.gray;
    public string pathName;
    public List<Vector3> points = new List<Vector3>();
    public List<float> timeSpan = new List<float>();

    public float time;
    public float currentRecordTime;
    public float recordTime = 5f;

    private void RecordPoint(Vector3 point)
    {
        points.Add(point);
        timeSpan.Add(time);
    }

    private void Start()
    {
        // 移除LineRenderer初始化代码，仅保留初始点记录
        RecordPoint(transform.position);
    }

    public void Update()
    {
        time += Time.deltaTime;
        currentRecordTime += Time.deltaTime;

        // 原有轨迹记录逻辑不变（按时间间隔+距离阈值记录点）
        if (currentRecordTime >= recordTime)
        {
            currentRecordTime = 0;
            // 避免空列表异常（理论上Start已初始化，此处做双重保障）
            if (points.Count > 0 && Vector3.Distance(transform.position, points[^1]) > distance)
            {
                RecordPoint(transform.position);
            }
        }
    }

    [Button("清除轨迹")]
    public void Clear()
    {
        timeSpan.Clear();
        points.Clear();
        time = 0;
        RecordPoint(transform.position);
    }


    [Button("导出轨迹")]
    public void OutPutPos()
    {
        // 避免空列表异常（若仅初始点则无需删除，此处保留原逻辑但加判断）
        if (points.Count > 1)
        {
            points.RemoveAt(0);
        }

        var path = new UavPath(points, timeSpan);
        // 序列化为JSON并导出到StreamingAssets
        var json = JsonUtility.ToJson(path);
        // 确保StreamingAssets文件夹存在（避免路径错误）
        if (!System.IO.Directory.Exists(Application.streamingAssetsPath))
        {
            System.IO.Directory.CreateDirectory(Application.streamingAssetsPath);
        }

        var filePath = System.IO.Path.Combine(Application.streamingAssetsPath, $"{pathName}OutPath.json");
        Debug.Log($"【轨迹导出】路径已保存至：{filePath}");
        System.IO.File.WriteAllText(filePath, json);
    }

    public void OnDrawGizmos()
    {
        // 按静态开关控制是否显示轨迹，保留原逻辑
        if (!StaticState.ShowPathLine)
            return;

        Gizmos.color = color;

        // Gizmo绘制轨迹线（遍历所有点连接线段）
        for (var i = 0; i < points.Count; i++)
        {
            // 避免越界（仅连接当前点与下一个点）
            if (i < points.Count - 1)
            {
                Gizmos.DrawLine(points[i], points[i + 1]);
            }
        }

        // 2. 额外绘制：最后一个记录点 → 当前物体位置的实时连线
        if (points.Count > 0) // 确保有记录点才绘制，避免空列表异常
        {
            var lastRecordedPoint = points[^1];
            var currentObjectPos = transform.position;

            Gizmos.DrawLine(lastRecordedPoint, currentObjectPos);
        }
    }
}